package com.jieshuibao.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.AnswerExample;
import com.jieshuibao.model.db.AttentionExample;
import com.jieshuibao.model.db.Category;
import com.jieshuibao.model.db.Counselor;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.Level;
import com.jieshuibao.model.db.LevelExample;
import com.jieshuibao.model.db.Opinion;
import com.jieshuibao.model.db.QuestionEx;
import com.jieshuibao.model.db.QuestionExample;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.AttentionExample.Criteria;
import com.jieshuibao.model.domain.Article;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.OpinionRequest;
import com.jieshuibao.model.domain.PagePhone;
import com.jieshuibao.model.domain.PageRequest;
import com.jieshuibao.model.domain.PersonalReq;
import com.jieshuibao.model.domain.ScoreRequest;
import com.jieshuibao.model.domain.UserDetails;
import com.jieshuibao.model.domain.UserLevel;
import com.jieshuibao.service.AnswerUserService;
import com.jieshuibao.service.ArticelService;
import com.jieshuibao.service.AttentionService;
import com.jieshuibao.service.CategoryService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.CounselorService;
import com.jieshuibao.service.LevelService;
import com.jieshuibao.service.OpinionService;
import com.jieshuibao.service.QuestionUserService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.util.DeleteHtmlUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
@RequestMapping(value = "/personal")
public class PersonalController {

	@Resource
	private RedisService redisService;

	@Resource
	private UserService userService;

	@Resource
	private CounselorService counselorService;

	@Resource
	private CategoryService categoryService;

	@Resource
	private CounselorDutyService counselorDutyService;

	@Resource
	private ArticelService articelService;

	@Resource
	private AttentionService attentionService;

	@Resource
	private OpinionService opinionService;

	@Resource
	private AnswerUserService answerUserService;

	@Resource
	private QuestionUserService questionUserService;
	
	@Resource
	private LevelService levelService;

	// 咨询师修改价格
	@RequestMapping(value = "/consultMoney", method = RequestMethod.POST)
	@ResponseBody
	public Object updateConsultMoney(HttpServletRequest request,
			@RequestBody ScoreRequest scoreRequest) {
		HashMap<String, String> map = new HashMap<String, String>();

		try {
			CookieUser cookieUser = (CookieUser) request
					.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			int role = cookieUser.getRole();

			if (role == 2) {
				Level level = userService.getLevelMoney(phoneNumber);
				int money = scoreRequest.getMoney();

				if (level != null && money > 0) {
					Integer levelmoney = level.getMoney();
					if (money <= levelmoney) {
						String counselorUuid = cookieUser.getCounselorUuid();
						Counselor counselor = new Counselor();
						counselor.setUuid(counselorUuid);
						counselor.setConsultMoney(money);
						counselorService.updateCounselor(counselor);
						map.put("code", BaseRes.SUCCESS_CODE);
						map.put("des", "修改成功");
						return map;
					} else {
						map.put("code", "4");
						map.put("des", "您的价格不能高于" + levelmoney + "元");
						return map;
					}

				} else {
					map.put("code", BaseRes.ERRORPARAM_CODE);
					map.put("des", BaseRes.ERRORPARAM_DES);
					return map;
				}
			} else {
				map.put("code", BaseRes.ERRORPARAM_CODE);
				map.put("des", "只有咨询师可以修改价格");
				return map;
			}

		} catch (Exception e) {

			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}
		return map;
	}

	// 个人主页
	@RequestMapping(value = "/home", method = RequestMethod.POST)
	@ResponseBody
	public Object homePage(HttpServletRequest request,
			@RequestBody PageRequest pageRequest) {
		HashMap<String, Object> map = new HashMap<String, Object>();

		try {
			CookieUser cookieUser = (CookieUser) request
					.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			String phone = pageRequest.getPhone();

			UserDetails details = null;
			PagePhone pagePhone = new PagePhone();
			pagePhone.setPageIndex(0);
			pagePhone.setPageSize(3);
			if (phone == null || phone.equals("")) {
				details = userService.getPersonalUser(phoneNumber);
				pagePhone.setId(phoneNumber);
			} else {
				details = userService.getPersonalUser(phone);
				pagePhone.setId(phone);
			}
			if (details != null) {
				String adept = details.getAdept();
				if (adept != null && !adept.equals("")) {
					String[] adeps = adept.split(",");
					HashMap<String, String> hashmap = new HashMap<String, String>();
					for (String categoyrUuid : adeps) {
						if (categoyrUuid != null) {
							Category categoryById = categoryService
									.getCategoryById(categoyrUuid);
							if (categoryById != null) {
								hashmap.put(categoyrUuid,
										categoryById.getName());
							}

						}

					}
					details.setAdepts(hashmap);
				}

				String counselorDuty = details.getCounselorDuty();
				if (StringUtils.isNotBlank(counselorDuty)) {
					String counselorDutyName = counselorDutyService
							.getCounselorDutyName(counselorDuty);
					details.setCounselorDuty(counselorDutyName);
				}

			}
			if (phone != null && !phone.equals("")
					&& !phone.equals(phoneNumber)) {

				AttentionExample attentionExample = new AttentionExample();
				Criteria createCriteria = attentionExample.createCriteria();
				createCriteria.andBeAttentionNumEqualTo(phone);
				createCriteria.andAttentionNumEqualTo(phoneNumber);
				int countAttention = attentionService
						.countAttention(attentionExample);
				if (countAttention > 0) {
					map.put("isAttention", 1);// 不显示关注
				} else {
					map.put("isAttention", 0);// 显示
				}
				map.put("self", 0);//别人
			} else {
				// 是自己
				map.put("isAttention", 1);
				map.put("self", 1);//自己
			}

			List<Article> articles = articelService
					.getArticleByPhone(pagePhone);
			if (articles != null) {
				for (Article article : articles) {
					String descriptionHtml = article.getDescription();
					if (descriptionHtml != null && !descriptionHtml.equals("")) {
						String description = DeleteHtmlUtil
								.getTextFromHtml(descriptionHtml);
						article.setDescription(description);
					}
					UserLevel userLevel = article.getUserLevel();
					if (userLevel != null) {
						String counselorDuty = userLevel.getCounselorDuty();
						if (counselorDuty != null && !counselorDuty.equals("")) {
							if (!counselorDuty.contains(" ")) {
								StringBuilder stringBuilder = new StringBuilder();
								String[] split = counselorDuty.split(",");
								if (split != null) {

									for (String id : split) {
										if (id != null && !id.equals("")) {
											Duty duty = counselorDutyService
													.getDutyById(id);
											if (duty != null) {

												stringBuilder.append(duty
														.getDutyName() + " ");
											}
										}

									}
									userLevel.setCounselorDuty(stringBuilder
											.toString());
								}
							}
						}

						article.setUserLevel(userLevel);
					}
				}
			}
			map.put("users", details);
			// map.put("articles", articles);
			map.put("code", "1");
			map.put("des", "成功");
			return map;

		} catch (Exception e) {

			e.printStackTrace();
			map.put("code", "0");
			map.put("des", "网路繁忙");
		}
		return map;
	}

	/**
	 * 意见反馈
	 * 
	 * @param request
	 * @param opinionRequest
	 * @return
	 */
	@RequestMapping(value = "/opinion", method = RequestMethod.POST)
	@ResponseBody
	public Object addOpinon(HttpServletRequest request,
			@RequestBody OpinionRequest opinionRequest) {
		HashMap<String, String> map = new HashMap<String, String>();

		try {
			CookieUser cookieUser = (CookieUser) request
					.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();

			String contact = opinionRequest.getContact();
			String content = opinionRequest.getContent();
			String uuid = UUIDGenerator.getUUID();
			Opinion opinion = new Opinion();
			opinion.setUuid(uuid);
			opinion.setUserId(phoneNumber);
			opinion.setContent(content);
			opinion.setContact(contact);
			opinion.setDate(new Date());
			opinion.setStatus("0");
			opinionService.addOpinion(opinion);
			map.put("code", "1");
			map.put("des", "提交成功");

		} catch (Exception e) {

			e.printStackTrace();
			map.put("code", "0");
			map.put("des", "网路繁忙");
		}
		return map;
	}

	@RequestMapping(value = "/user/adop")
	@ResponseBody
	public Object personalQuestionAdop(HttpServletRequest request,
			@RequestBody(required = false) PersonalReq req) {

		BaseRes<List<QuestionEx>> res = new BaseRes<List<QuestionEx>>();
		try {
			CookieUser cookieUser = (CookieUser) request
					.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			if (req == null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			String uuid = req.getUuid();
			if (StringUtils.isBlank(uuid)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}

			int sinceId = req.getSinceId();
			int maxId = req.getMaxId();

			AnswerExample answerExample = new AnswerExample();
			answerExample
					.setOrderByClause("question_user.lookNum desc,answer.date desc");
			answerExample.setPageIndex(sinceId - 1);
			answerExample.setPageSize(maxId - sinceId + 1);
			com.jieshuibao.model.db.AnswerExample.Criteria createCriteria = answerExample
					.createCriteria();
			createCriteria.andStatusEqualTo(2);
			createCriteria.andPhoneNumberEqualTo(uuid);
			createCriteria.andDelFlagEqualTo(Global.SHOW);
			QuestionExample questionExample = new QuestionExample();
			com.jieshuibao.model.db.QuestionExample.Criteria createCriteria2 = questionExample
					.createCriteria();
			createCriteria2.andStatusEqualTo(3);
			createCriteria2.andDelFlagEqualTo(Global.SHOW);
			createCriteria2
					.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);

			List<QuestionEx> data = answerUserService.getUserQuestionAadops(
					answerExample, questionExample);
			for (QuestionEx questionEx : data) {
				String uuid2 = questionEx.getUuid();

				QuestionUserKey questionUserKey2 = new QuestionUserKey();
				questionUserKey2.setPhoneNumber(phoneNumber);
				questionUserKey2.setQuestionUuid(uuid2);
				QuestionUserKey questionUserKey = questionUserService
						.getQuestionUserKeys(questionUserKey2);
				if (questionEx.getPhoneNumber().equals(phoneNumber)
						|| questionUserKey != null) {
					questionEx.setStatus(1);// 自己公开的和查看过的

				} else {
					questionEx.setStatus(2);// 没有偷看过的
				}
			}

			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			res.setData(data);
			res.setMaxId(sinceId + data.size() - 1);
			res.setSinceId(sinceId);
			res.setRows(data.size());

			return res;
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			return res;
		}

	}
		//获取咨询师级别价格
	@ResponseBody
	@RequestMapping(value="/level",method=RequestMethod.POST)
	public Object getLevels(){
		BaseRes<List<Level>> res = new BaseRes<List<Level>>();
		
		try {
			LevelExample levelExample = new LevelExample();
			levelExample.setOrderByClause("money");
			List<Level> data = levelService.getLevels(levelExample);
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			res.setData(data);
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
		}
		return res;
	}
	
}
